package api

const APITmpl = `// @ts-ignore
/* eslint-disable */
import { Graphql } from '../utils';

const gqlGet{{.Model.Name}}List = ` + "`" + `query get_item_list($limit: Int = 10, $offset: Int = 0{{- with .Model.Fields}}{{- range .}}{{- if .IsSearch}}, ${{.Name}}: {{.Type}}{{- end}}{{- end}}{{- end}}) {
  {{.Model.GraphqlName}}(order_by: {updated_at: desc}, limit: $limit, offset: $offset{{.Model.GenGraphqlSearchWhere false}}) {
    {{- with .Model.Fields}}
    {{- range .}}
    {{.Name}}
    {{- end}}
    {{- end}}
  }
  {{.Model.GraphqlName}}_aggregate({{.Model.GenGraphqlSearchWhere true}}) {
    aggregate {
      count
    }
  }
}` + "`" + `;

const gqlCreate{{.Model.Name}} = ` + "`" + `mutation create_item({{.Model.GenGraphqlInsertParamDefinations}}) {
  insert_{{.Model.GraphqlName}}_one(object: { {{.Model.GenGraphqlInsertParams}} }) {
    id
  }
}` + "`" + `;

const gqlUpdate{{.Model.Name}} = ` + "`" + `mutation update_item_by_pk($id: uuid!, {{.Model.GenGraphqlUpdateParamDefinations}}) {
  update_{{.Model.GraphqlName}}_by_pk(pk_columns: {id: $id}, _set: { {{.Model.GenGraphqlUpdateParams}} }) {
    id
  }
}` + "`" + `;

const gqlDelete{{.Model.Name}} = ` + "`" + `mutation delete_item_by_pk($id: uuid!) {
  delete_{{.Model.GraphqlName}}_by_pk(id: $id) {
    id
  }
}` + "`" + `;

export async function get{{.Model.Name}}List(params: API.{{.Model.Name}}Item & API.PageInfo) {
  const gqlVar = {
    limit: params.pageSize ? params.pageSize : 10,
    offset: params.current && params.pageSize ? (params.current - 1) * params.pageSize : 0,
    {{- with .Model.Fields}}
    {{- range .}}
    {{- if .IsSearch}}
    {{.Name}}: params.{{.Name}} ? '%' + params.{{.Name}} + '%' : '%%',
    {{- end}}
    {{- end}}
    {{- end}}
  };

  return Graphql<API.{{.Model.Name}}ListResult>(gqlGet{{.Model.Name}}List, gqlVar);
}

export async function create{{.Model.Name}}(params: API.{{.Model.Name}}Item) {
  const gqlVar = {
    {{- with .Model.Fields}}
    {{- range .}}
    {{- if not .NotInsert}}
    {{- if .IsPageRequired}}
    {{.Name}}: params.{{.Name}},
    {{- else}}
    {{.Name}}: params.{{.Name}} ? params.{{.Name}} : null,
    {{- end}}
    {{- end}}
    {{- end}}
    {{- end}}
  };

  return Graphql<API.Create{{.Model.Name}}Result>(gqlCreate{{.Model.Name}}, gqlVar);
}

export async function update{{.Model.Name}}(params: API.{{.Model.Name}}Item) {
  const gqlVar = {
    id: params.id,
    {{- with .Model.Fields}}
    {{- range .}}
    {{- if not .NotUpdate}}
    {{- if .IsPageRequired}}
    {{.Name}}: params.{{.Name}},
    {{- else}}
    {{.Name}}: params.{{.Name}} ? params.{{.Name}} : null,
    {{- end}}
    {{- end}}
    {{- end}}
    {{- end}}
  };

  return Graphql<API.Update{{.Model.Name}}Result>(gqlUpdate{{.Model.Name}}, gqlVar);
}

export async function delete{{.Model.Name}}(id: string) {
  return Graphql<API.Delete{{.Model.Name}}Result>(gqlDelete{{.Model.Name}}, { id });
}`
